/*
 * 
 * 
 * @author: Oren Zamir
 */
package org.valire.usermanagement.services;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.orm.jpa.JpaCallback;
import org.valire.usermanagement.beans.User;
import org.valire.util.persistency.GenericJpaDaoImpl;


/**
 * The Class UserDao.
 */
@SuppressWarnings("unchecked")
public class UserDao extends GenericJpaDaoImpl<User, Integer> {

	/**
	 * Instantiates a new user dao.
	 */
	public UserDao() {
		super(User.class);
	}

	/**
	 * Gets the user entity bean.
	 * 
	 * @param userName
	 *            the user name
	 * @return the user bean
	 */
	public User getUser(String userName) {
		List<User> results = getJpaTemplate().find("select user from org.valire.usermanagement.beans.User user where user.userName = ?1", userName);
		if (results.size() == 0) {
			return null;
		}
		return results.get(0);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.valire.util.persistency.GenericJpaDaoImpl#update(java.lang.Object)
	 */
	@Override
	public void update(final User user) {
		if (user.getPassword() == null) {
			getJpaTemplate().execute(new JpaCallback<User>() {
				@Override
				public User doInJpa(EntityManager em) throws PersistenceException {
					Query query = em.createQuery("UPDATE org.valire.usermanagement.beans.User SET firstName = :firstName,lastName = :lastName, emailAddress = :emailAddress where userName = :userName");

					query.setParameter("firstName", user.getFirstName());
					query.setParameter("lastName", user.getLastName());
					query.setParameter("sapName", user.getSapName());
					query.setParameter("sapLanguage", user.getSapName());
					query.setParameter("emailAddress", user.getEmail());
					query.setParameter("userName", user.getUserName());

					query.executeUpdate();

					return null;
				}

			});
		} else {
			merge(user);
		}
	}

	/**
	 * Sets the password.
	 * 
	 * @param newPassword
	 *            the new password
	 */
	public void setPassword(final User user) {
		getJpaTemplate().execute(new JpaCallback<User>() {
			@Override
			public User doInJpa(EntityManager em) throws PersistenceException {
				Query query = em.createQuery("UPDATE org.valire.usermanagement.beans.User SET password = :password  where userName = :userName");

				query.setParameter("password", user.getPassword());
				query.setParameter("userName", user.getUserName());
			
				query.executeUpdate();

				return null;
			}
		});
	}
}
